package cn.cpf.cfets;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * <b>Description : </b>
 * <p>
 * <b>created in </b> 2021/2/5
 *
 * @author CPF
 * @since 1.0
 **/
public class LoopStack<T> {

    private final Object[] objects;

    private final int size;

    private int idx;

    public LoopStack(int size) {
        this.size = size;
        objects = new Object[size];
    }

    public void add(T t) {
        objects[idx] = t;
        idx++;
        assert idx <= size;
        if (idx >= size) {
            idx %= size;
        }
    }

    public T prev(int num) {
        num %= size;
        int d = idx - num;
        if (d < 0) {
            d += size;
        }
        return (T) objects[d];
    }

    public List<T> prevList(int num) {
        List<T> list = new ArrayList<>(num);
        for (int i = num; i > 0; i--) {
            list.add(prev(i));
        }
        return list;
    }

    public T peek(){
        return (T) objects[idx];
    }

    @Override
    public String toString() {
        return "LoopStack{" +
                "objects=" + IntStream.range(0, 19).mapToObj(this::prev).map(Objects::toString).collect(Collectors.joining()) +
                ", size=" + size +
                ", idx=" + idx +
                '}';
    }

}
